<?php
namespace Crm\Controller;

use Zend\View\Model\ViewModel;
use Crm\Common\UploaderHelper;

/**
 * 商城管理
 */
class ShopController extends AbstractController
{
    /**
     * 商品列表
     */
    public function listAction()
    {
        $organization = $this->getOrganizationTable()->findAllDisplay(2);
        $good_cate = $this->getCategoryTable()->findAllDisplay();
        return new ViewModel(array(
            'organization' => $organization,
            'good_cate' => $good_cate
        ));
    }
    
    /**
     * AJAX 请求商品数据
     */
    public function ajaxProductListAction()
    {
        $request = $this->request->getPost()->toArray();
    
        (int) $org_id = isset($request['org_id']) ? $request['org_id'] : 0;
        $product_name = isset($request['product_name']) ? $request['product_name'] : '';
        (int) $page = isset($request['page']) ? $request['page'] : 1;
        
        $query = array(
            'org_id' => $org_id,
            'product_name' => $product_name,
            'page' => $page,
            'admin_org_id' => $this->adminOrgId
        );
    
        $paginator = $this->getProductTable()->findShopGoods($query);
        $result = array(
            'paginator' => $paginator
        );
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * 新增商品
     */
    public function addAction()
    {
        $organization = $this->getOrganizationTable()->findAllDisplay(2, $this->adminOrgId);
        $good_cate = $this->getCategoryTable()->findAllDisplay();
        
        return new ViewModel(array(
            'organization' => $organization,
            'good_cate' => $good_cate
        ));
    }
    
    
    public function insertAction()
    {
        $request = $this->getRequest();
    
        if ($request->isPost()) {
            $data = $this->request->getPost()->toArray();
            // unset($data['file']);
            // array_diff($data,);
    
            $data1 = array(
                'file' => '',
                'category_id' => ''
            );
            $goods_data = array_diff_key($data, $data1);
            $goods_data['product_type'] = 2; 
            $result = $this->getProductTable()->create($goods_data);
    
            if ($result) {
    
                // 产品和分类关系表
                $relation_data['category_id'] = $data['category_id'];
                $relation_data['product_id'] = $result;
                $this->getProductCategoryTable()->create($relation_data);
    
                $this->flashMessenger()->addSuccessMessage("保存成功！");
                return $this->redirect()->toRoute('crm/shop');
            } else {
    
                $this->flashMessenger()->addErrorMessage("保存失败！");
                return $this->redirect()->toRoute('crm/shop', array(
                    'action' => 'add'
                ));
            }
        }
    }
    
    
    /**
     * 复制商品
     */
    public function copyGoodsAction(){
    
        $request = $this->getRequest()->getQuery();
        (int) $id = $request['product_id'];
        $data = $this->getProductTable()->findOneShopToArray($id);
    
        $data1 = array(
            'product_id' => '',
            'category_id' => ''
        );
        $goods_data = array_diff_key($data[0], $data1);
        $result = $this->getProductTable()->create($goods_data);
    
        if ($result) {
            
            // 产品和分类关系表
            $relation_data['category_id'] = $data[0]['category_id'];
            $relation_data['product_id'] = $result;

            $this->getProductCategoryTable()->create($relation_data);
            
            $this->flashMessenger()->addSuccessMessage("复制成功！");
        } else {
            $this->flashMessenger()->addErrorMessage("复制失败！");
        }
    
        return $this->redirect()->toRoute('crm/shop', array(
            'action' => 'list'
        ));
    
    }
    
    /**
     * 编辑商品
     */
    public function editAction()
    {
        $request = $this->getRequest()->getQuery();
        (int) $id = $request['product_id'];
        $product = $this->getProductTable()->findOne($id);
        
        $organization = $this->getOrganizationTable()->findAllDisplay(2);
        $good_cate = $this->getCategoryTable()->findAllDisplay();
    
        return new ViewModel(array(
            'organization' => $organization,
            'good_cate' => $good_cate,
            'product' => $product
        ));
    }
    
    public function updateAction()
    {
        $request = $this->getRequest();
    
        if ($request->isPost()) {
            $data = $this->request->getPost()->toArray();
    
            $data1 = array(
                'file' => '',
                'category_id' => '',
                'product_id' => ''
            );
    
            $product_data = array_diff_key($data, $data1);
            $product_data['update_time'] = date("Y-m-d H:i:s");
            (int) $id = $data['product_id'];
            $result = $this->getProductTable()->updateById($product_data, $id);
    
            if ($result) {
    
                // 产品和分类关系表
//                 $where = array(
//                     'product_id' => $id,
//                     'category_id' => $data['category_id']
//                 );
                
                $where = array(
                    'product_id' => $id
                );
                
                $cate_data = array(
                    'category_id' => $data['category_id']
                );
                
                //该产品是否已经有分类
                $has_relation = $this->getProductCategoryTable()->findHas($where);
            
                if ($has_relation) {
                    $this->getProductCategoryTable()->updateByProductId($cate_data, $id);
                }else {
                    $this->getProductCategoryTable()->create($where);
                }
    
                $this->flashMessenger()->addSuccessMessage("编辑成功！");
                return $this->redirect()->toRoute('crm/shop', array(
                    'action' => 'list'
                ));
            } else {
    
                $this->flashMessenger()->addErrorMessage("编辑失败！");
    
                return $this->redirect()->toUrl("list?product_id=$id");
            }
        }
    }
    
    
    public function removeAction()
    {}
    
    /**
     * 商品分类
     */
    public function cateListAction()
    {
        return new ViewModel();
    }
    
    /**
     * 商品分类AJAX 请求数据
     */
    public function ajaxCateListAction()
    {
        $request = $this->request->getPost()->toArray();
    
        $category_name = isset($request['category_name']) ? $request['category_name'] : '';
        (int) $page = isset($request['page']) ? $request['page'] : 1;
        $query = array(
            'category_name' => $category_name,
            'page' => $page
        );
    
        $paginator = $this->getCategoryTable()->find($query);
        $result = array(
            'paginator' => $paginator
        );
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * 新增商品分类
     */
    public function addCateAction()
    {
        //$organization = $this->getOrganizationTable()->findAllDisplay(2);
        $organization = $this->getOrganizationTable()->findAllDisplay(2, $this->adminOrgId);

        return new ViewModel(array(
            'org' => $organization
        ));
    }
    
    /**
     * 分类数据入库
     */
    public function insertCateAction()
    {
        $request = $this->getRequest();
    
        if ($request->isPost()) {
            $data = $this->request->getPost()->toArray();
            $result = $this->getCategoryTable()->create($data);
            if ($result) {
    
                $this->flashMessenger()->addSuccessMessage("保存成功！");
                return $this->redirect()->toRoute('crm/shop', array(
                    'action' => 'cateList'
                ));
            } else {
    
                $this->flashMessenger()->addErrorMessage("保存失败！");
                return $this->redirect()->toRoute('crm/shop', array(
                    'action' => 'addCate'
                ));
            }
        }
    }
    
    /**
     * 编辑分类
     */
    public function editCateAction()
    {
        $request = $this->getRequest()->getQuery();
        (int) $id = $request['category_id'];
        
        $category = $this->getCategoryTable()->findOne($id);
    
        //$organization = $this->getOrganizationTable()->findAll();
        $organization = $this->getOrganizationTable()->findAllDisplay(2);
        
        return new ViewModel(array(
            'organization' => $organization,
            'category' => $category
        ));
    }
    
    /**
     * 编辑商品分类入库
     */
    public function updateCateAction()
    {
        $request = $this->getRequest();
    
        if ($request->isPost()) {
            $data = $this->request->getPost()->toArray();
    
            $data1 = array(
                'category_id' => ''
            );
            $cate_data = array_diff_key($data, $data1);
    
            (int) $id = $data['category_id'];
            $result = $this->getCategoryTable()->updateById($cate_data, $id);
    
            if ($result) {
    
                $this->flashMessenger()->addSuccessMessage("编辑成功！");
                return $this->redirect()->toRoute('crm/shop', array(
                    'action' => 'cateList'
                ));
            } else {
    
                $this->flashMessenger()->addErrorMessage("编辑失败！");
    
                return $this->redirect()->toUrl("cateList?category_id=$id");
            }
        }
    }
    
    /**
     * AJAX 图片上传
     */
    public function ajaxUploadAction()
    {
        $request = $this->getRequest();
        $file_path = $request->getPost('path');
        // 不允许目录操作符
        $file_path = str_replace('../', '', $file_path);
        $file_path = str_replace('./', '', $file_path);
    
        // $file_ext = substr(strstr(strstr($file_data,';',true),'/'),1);
    
        $path_format = UploaderHelper::getPathFormat($file_path . "/{yyyy}{mm}/{time}{rand:6}");
    
        $config = array(
            "pathFormat" => $path_format,
            "maxSize" => 2048000,
            "allowFiles" => [
                ".png",
                ".jpg",
                ".jpeg",
                ".gif"
            ]
        )
        // "oriName" => 'headimg.'.$file_ext
        ;
    
        $file_data = "file";
        // base64
        $up = new UploaderHelper($file_data, $config);
        $file_info = $up->getFileInfo();
        if ($file_info['state'] === 'SUCCESS') {
    
            $response = $file_info;
            die(json_encode($response));
        } else {
    
            $response = array(
                'info' => '图片上传失败，请重新上传。',
                'status' => false
            );
            die(json_encode($response));
        }
    }
    
}